package org.mineground.listener;

import org.bukkit.ChatColor;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.mineground.Main;
import org.mineground.PermissionNodes;
import org.mineground.player.MinegroundPlayer;

/**
 * @file EntityListener.java (22.01.2012)
 * @author Daniel Koenen
 *
 */
public class EntityListener implements Listener {
    @EventHandler(priority = EventPriority.HIGH)
    public void onEntityDamage(final EntityDamageEvent damageEvent) {
        if (damageEvent.isCancelled()) {
            return;
        }
        
        Entity eventEntity = damageEvent.getEntity();
        
        if (!(eventEntity instanceof Player)) {
            return;
        }
        
        Player damagedPlayer = (Player) eventEntity;
        
        if (!Main.getInstance().containsPlayer(damagedPlayer)) {
            damageEvent.setCancelled(true);
            return;
        }
        
        MinegroundPlayer playerInstance = Main.getInstance().getPlayer(damagedPlayer);
        
        if (playerInstance.getGodToggle()) {
            damageEvent.setCancelled(true);
            return;
        }
       
        if (damageEvent instanceof EntityDamageByEntityEvent) {
            EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) damageEvent;
            
            if ((subEvent.getDamager() instanceof Player) && !playerInstance.getPvPToggle() && !damagedPlayer.hasPermission(PermissionNodes.PERMISSION_FORCE_PVP)) {
                ((Player) subEvent.getDamager()).sendMessage(ChatColor.RED + "This player has disabled PvP.");
                damageEvent.setCancelled(true);
            }
        }
    }
    
    @EventHandler(priority = EventPriority.HIGH)
    public void onEntityDeath(EntityDeathEvent deathEvent) {
        if (deathEvent.getEntity() instanceof Player) {
            Player deathPlayer = (Player) deathEvent.getEntity();
            
            if (Main.getInstance().containsPlayer(deathPlayer)) {
                Main.getInstance().getPlayer(deathPlayer).setDieWorld(deathPlayer.getWorld());
            }
            if (deathPlayer.getDisplayName() != null) {
            	Main.getInstance().getIRCHandler().sendEchoMessage("Player " + deathPlayer.getDisplayName() + " has died!");
            }
            
            if (deathEvent.getDroppedExp() > 150) {
                deathEvent.setDroppedExp(150);
                deathPlayer.sendMessage(ChatColor.RED + "* Your experience-point drops have been reduced to 150 xp to avoid damage in the related chunk.");
            }
        }
    }
    
}
